package boot

import (
	"appService/src/application/admin/admin"
	"appService/src/application/admin/admin/adminModels"
	"appService/src/application/app"
	"appService/src/application/login"
	"appService/src/authValid/dataAuth"
	"appService/src/global"
	"appService/src/global/router"
	"appService/src/libs/utils"
	"appService/src/middleware"
	"appService/src/orm"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/guid"
	"os"
	"xorm.io/builder"
)

// 初始化

func Init() {
	syncDb()     // 同步数据库
	initRouter() //注册路由
}

// 获取数据库表 模型 列表
func bansList() []interface{} {
	list := make([]interface{}, 0)
	list = append(list, app.GetModeBans()...)   //app 模型
	list = append(list, admin.GetModeBans()...) //admin 模型
	return list
}

//获取路由列表
func routerList() []*router.Router {
	routerList := make([]*router.Router, 0)
	routerList = append(routerList, app.GetRouterList()...)   //APP 模块路由
	routerList = append(routerList, login.GetRouterList()...) //login 模块路由
	routerList = append(routerList, admin.GetRouterList()...) //admin 模块路由
	return routerList
}

// 同步数据库
func syncDb() {
	g.Log().Info("┏━ 开始同步数据库……")
	bansList := bansList()
	err := orm.Db.Sync2(bansList...)
	if err != nil {
		g.Log().Errorf("┣━ ✖ 同步数据库表失败，错误：%v", err)
		os.Exit(1)
	}
	g.Log().Info("✿ 同步数据库表完成")
}

//注册路由
func initRouter() {
	g.Log().Info("┏━ 开始注册路由……")
	list := routerList()
	//设置所有路由 为 禁用
	_, err := orm.Db.Table(new(adminModels.Api)).Cols("enable").Update(map[string]int{"enable": 2})
	if err != nil {
		g.Log().Errorf("┣━ 设置路由状态失败，错误：%v", err)
		os.Exit(1)
	}
	// 注册全局中间件
	g.Server().Use(middleware.MiddlewareHttpLog)
	//注册主程序路由
	g.Server().Group(global.ApiRootPath, func(group *ghttp.RouterGroup) {
		regRouterNum := 0
		for k, v := range list {
			//注册路由
			switch v.Method {
			case router.POST:
				group.POST(v.Router, v.Object, v.Func)
				break
			case router.PUT:
				group.PUT(v.Router, v.Object, v.Func)
				break
			case router.PATCH:
				group.PATCH(v.Router, v.Object, v.Func)
				break
			case router.GET:
				group.GET(v.Router, v.Object, v.Func)
				break
			case router.DELETE:
				group.DELETE(v.Router, v.Object, v.Func)
				break
			}
			apiRoute := global.ApiRootPath + v.Router
			authCode := utils.RouteToAuthCode(apiRoute, v.Method)
			if v.Visit == 0 {
				v.Visit = dataAuth.PUBLIC
			}
			if v.IsSign == 0 {
				v.IsSign = 1
			}
			//保存路由到数据库
			api := &adminModels.Api{
				Id:          guid.S(),
				AuthGroupId: v.AuthGroupId,
				Title:       v.Title,
				AuthCode:    authCode,
				Router:      apiRoute,
				Method:      v.Method,
				Visit:       v.Visit,
				IsSign:      v.IsSign,
				IsShow:      1,
				Enable:      1,
				Sort:        k + 1,
			}
			a := new(adminModels.Api)
			a.Router = apiRoute
			a.AuthCode = authCode
			has, err := orm.Db.Get(a)
			if err != nil {
				g.Log().Errorf("┣━ 获取路由 [ %v ] => [ %v ] 信息失败，错误：%v", v.Title, apiRoute, err)
				os.Exit(1)
			}
			if has {
				cols := "auth_group_id,title,auth_code,router,method,enable,sort"
				_, err = orm.Db.Where(builder.Eq{"id": a.Id}).Cols(cols).Update(api)
			} else {
				_, err = orm.Db.Insert(api)
			}
			if err != nil {
				g.Log().Errorf("┣━ 保存路由 [ %v ] => [ %v ] 信息失败，错误：%v", v.Title, apiRoute, err)
				os.Exit(1)
			}
			regRouterNum++
			//g.Log().Infof("┣━ 路由 [ %v ] => [ %v ] 注册成功", v.Title, apiRoute)
		}
		g.Log().Infof("┣━ (◕‿◕✿) 成功注册 [ %v ] 个路由", regRouterNum)
	})
	g.Log().Infof("┗━ 路由注册完成")
}
